﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using IKEA.FileExchange.Security;
using System.Collections.Generic;
using IKEA.FileExchange.Web;
using IKEA.FileExchange.Domain.FileCleanupManagement;
using Microsoft.SharePoint;
using IKEA.FileExchange.Domain;
using IKEA.FileExchange.Domain.FilePackage;
using IKEA.FileExchange.Domain.Files;
using IKEA.FileExchange.Domain.DownloadTickets;


public partial class controls_UploadWizardControl : System.Web.UI.UserControl
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string weekly = string.Concat(DateTime.Now.AddDays(7).ToShortDateString()," (in 7 days)");
            string monthly = string.Concat(DateTime.Now.AddDays(31).ToShortDateString()," (in one month)");

            ListItem liCleanupWeek = new ListItem(weekly , CleanupRule.Week.ToString());
            ListItem liCleanupMonth = new ListItem(monthly , CleanupRule.Month.ToString());

            ddlCleanupDate.Items.Add(liCleanupWeek);
            ddlCleanupDate.Items.Add(liCleanupMonth);

            ProcessSourceParam();

            SetupControlsByUser();
            
            
        }

        
        
    }

    protected void SetupControlsByUser()
    {
        if (SPContext.Current.Web.CurrentUser.LoginName.ToLower() == "ikeafilesharemembership:ikea_partner")
        {
            cbConfidentialUpload.Checked = true;
        }
    }


    protected void ProcessSourceParam()
    {
        string source = Request.QueryString["source"];

        if (!string.IsNullOrEmpty(source))
        {
            int indexOfParamStart = source.IndexOf('?');

            if (indexOfParamStart >= 0)
            {
                string parameters = source.Substring(indexOfParamStart);

                if (parameters.Length > 0)
                {
                    parameters = parameters.Remove(0, 1);

                    string[] splittedParameters = parameters.Split('&');

                    Hashtable paramHash = new Hashtable();

                    foreach (string p in splittedParameters)
                    {
                        int paramSeparator = p.IndexOf('=');

                        paramHash[p.Substring(0,paramSeparator)] = p.Substring(paramSeparator).Remove(0,1);
                    }

                    if (paramHash["RootFolder"] != null)
                    {
                        hfTargetFolder.Value = paramHash["RootFolder"].ToString();
                    }
                }
            }
        }
    }

    protected void btnStart_Click(object sender, EventArgs e)
    {
        SPSecurity.RunWithElevatedPrivileges(
            delegate()
            {
                using (SPSite spSite = new SPSite(SPContext.Current.Site.Url))
                {
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        SPList packageList = IKEAFileStoreHelper.GetFilePackagesList(spWeb);

                        SPListItem newPackage = packageList.Items.Add();
                        newPackage["Title"] = string.Concat("Package ", (packageList.ItemCount + 1).ToString());
                        newPackage[FilePackageFieldNames.FilePackageRecipients] = txtRecipients.Text;
                        newPackage[FilePackageFieldNames.UploadComments] = txtUploadComments.Text;
                        newPackage[FilePackageFieldNames.IsConfidential] = cbConfidentialUpload.Checked;

                        if (cbSendManagementLink.Checked)
                        {
                            newPackage[FilePackageFieldNames.UploadPackageManagementEmail] = txtOwnerEmailAddress.Text;
                        }

                        newPackage.Update();

                        string[] uploadedFileIdents = hfUploadedFileIdents.Value.Split(';');

                        if (uploadedFileIdents.Length == 1)
                        {
                            if (string.IsNullOrEmpty(uploadedFileIdents[0]))
                            {
                                return;
                            }
                        }

                        if (uploadedFileIdents.Length > 0)
                        {
                            foreach (string ident in uploadedFileIdents)
                            {
                                if (string.IsNullOrEmpty(ident))
                                {
                                    continue;
                                }

                                Guid fileUniqueId = new Guid(ident);

                                SPList fileStore;

                                if (cbConfidentialUpload.Checked)
                                {
                                    fileStore = IKEAFileStoreHelper.GetConfidentialFileStore(spWeb);
                                }
                                else
                                {
                                    fileStore = IKEAFileStoreHelper.GetPublicFileStore(spWeb);
                                }

                                SPListItem fileListItem = fileStore.GetItemByUniqueId(fileUniqueId);

                                if (fileListItem != null)
                                {
                                    SPFieldLookupValue packageRef = new SPFieldLookupValue(newPackage.ID, newPackage.Title);
                                    fileListItem[FileFieldNames.FilePackageReference] = packageRef;
                                    fileListItem.Update();
                                }


                                
                            }

                            Dictionary<string,Guid> ticketsByRecipients = DownloadTicketManager.CreateDownloadTickets(newPackage, spWeb);

             

                            foreach (KeyValuePair<string, Guid> recipientTicket in ticketsByRecipients)
                            {
                                EmailHelper.SendEmail(recipientTicket.Key, recipientTicket.Value.ToString() , txtUploadComments.Text, NotificationType.NotificationToRecipient, spWeb);
                            }

                            if (cbSendManagementLink.Checked)
                            {
                                EmailHelper.SendEmail(txtOwnerEmailAddress.Text, newPackage.UniqueId.ToString(), "", NotificationType.NotificationToManager, spWeb);
                            }


                            string redirectUrl = string.Format("~/UploadSuccess.aspx?p={0}&source={1}", newPackage.UniqueId.ToString(), Request.QueryString["source"]);
                            Response.Redirect(redirectUrl);
                        }
                    }
                }
            }
        );

    }

    protected void Redirect()
    {
        string sourceUrl = Request.QueryString["source"];

        if (string.IsNullOrEmpty(sourceUrl))
        {
            Response.Redirect("~");
        }
        else
        {
            Response.Redirect(sourceUrl);
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Redirect();
    }
}
